﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Text;
using System.IO;

namespace blackhouse.Web.ViewState {
	public class ViewStateServicePersister : PageStatePersister {

		public const string VIEW_STATE_FIELD_NAME = "APP_STATE";

		private LosFormatter _formatter = null;

		public ViewStateServicePersister(Page page) : base(page) { }

		public override void Load() {
			if (_formatter == null) {
				_formatter = new LosFormatter();
			}

			if (null == Page.Request.Form[VIEW_STATE_FIELD_NAME]) {
				return;
			}

			long lRequestNumber = 0;
			try {
				lRequestNumber = Convert.ToInt64(Page.Request.Form[VIEW_STATE_FIELD_NAME]);
			}
			catch {
				return;
			}

			string _viewState = ViewStateServiceManager.GetViewStateServiceManager().GetViewState(lRequestNumber);

			if (_viewState == null)
				return;
			else
				ViewState = _formatter.Deserialize(_viewState);
		}

		public override void Save() {
			if (_formatter == null)
				_formatter = new LosFormatter();

			StringBuilder _viewState = new StringBuilder();
			StringWriter _writer = new StringWriter(_viewState);
			_formatter.Serialize(_writer, ViewState);
			long lRequestNumber = ViewStateServiceManager.GetViewStateServiceManager().SaveViewState(_viewState.ToString());

			Page.ClientScript.RegisterHiddenField(VIEW_STATE_FIELD_NAME, lRequestNumber.ToString());
		}

	}
}